package com.gem.controller;

import com.alibaba.fastjson.JSON;
import com.gem.domain.ClassInfo;
import com.gem.domain.Score;
import com.gem.domain.ScoreAPI;
import com.gem.domain.ScoreResult;
import com.gem.service.ClassInfoService;
import com.gem.service.ScoreService;
import com.gem.util.JSONResultUtil;
import com.gem.util.MessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Bravea❤ ·勇
 * Description: 学生成绩controller+考试平台接口
 * create
 * Modified By:
 */
@Controller
public class ScoreController {

    @Autowired
    private ClassInfoService classInfoService;

    @Autowired
    private JSONResultUtil result;

    @Autowired
    ScoreService scoreService;

    @RequestMapping("/score/list")
    public String show(Model model, Integer classId, ClassInfo classinfo, String classDate,
                       @RequestParam(value = "currentPage", defaultValue = "1") int currentPage) {
        if (classDate == null){
            classDate = "";
        }
        if (classId != null && classId >= 0) {
            List<Score> scores = scoreService.showScore(classId);
            ClassInfo c = classInfoService.findById(classId);
            if (scores != null && scores.size() > 0) {
                model.addAttribute("scores", scores);
            } else {
                model.addAttribute("info", "暂无学生成绩，请先添加！");
            }
            if (c != null) {
                model.addAttribute("className", c.getCId());
            } else {
                MessageUtil.returnInfoPage("3", "/career/findAll", "班级不存在", model);
                return "message";
            }
            model.addAttribute("classId", classId);//这是班级主键id！
        } else {
            MessageUtil.returnInfoPage("3", "/career/findAll", "传递参数为空", model);
            return "message";
        }
        if ((classinfo.getStartTime() == null || classinfo.getStartTime().equals(""))
                && (classinfo.getSName() == null || classinfo.getSName().equals(""))
                && (classinfo.getTName() == null || classinfo.getTName().equals(""))
                && (classinfo.getMName() == null || classinfo.getMName().equals(""))) {
            classinfo = null;
        }
        model.addAttribute("classDate", classDate);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("classinfo", classinfo);
        return "career/score";
    }

    @RequestMapping("/score/search")
    public String searchScore(Model model, String sname, Integer classId, ClassInfo classinfo, String classDate,
                              @RequestParam(value = "currentPage", defaultValue = "1") int currentPage) {
        if (sname == null || sname.trim().equals("")) {
            sname = "";
        }
        if (classDate == null){
            classDate = "";
        }
        List<Score> scores = scoreService.searchScore(classId, sname);
        ClassInfo c = classInfoService.findById(classId);
        if (scores != null && scores.size() > 0) {
            model.addAttribute("scores", scores);
        } else {
            model.addAttribute("info", "暂无学生成绩，请先添加！");
        }
        if (c != null) {
            model.addAttribute("className", c.getCId());
        } else {
            MessageUtil.returnInfoPage("3", "/career/findAll", "班级不存在", model);
            return "message";
        }
        if ((classinfo.getStartTime() == null || classinfo.getStartTime().equals(""))
                && (classinfo.getSName() == null || classinfo.getSName().equals(""))
                && (classinfo.getTName() == null || classinfo.getTName().equals(""))
                && (classinfo.getMName() == null || classinfo.getMName().equals(""))) {
            classinfo = null;
        }

        model.addAttribute("currentPage", currentPage);
        model.addAttribute("classDate", classDate);
        model.addAttribute("classId", classId);

        model.addAttribute("classinfo", classinfo);
       /* //代替下面三个条件
        model.addAttribute("classType", classinfo.getSName());
        model.addAttribute("classHeadTeacher", classinfo.getMName());
        model.addAttribute("classTeacher", classinfo.getTName());*/

        model.addAttribute("sname", sname);
        model.addAttribute("searchUrl", "/score/search?sname=" + sname);
        return "career/score";

    }

    @RequestMapping(value = "/factory/updateScore", method = RequestMethod.POST)
    @ResponseBody
    public Map<Integer, Boolean> update(@RequestBody ScoreAPI api, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");//同意哪些url能够跨域请求到本域
        response.setHeader("Access-Control-Allow-Methods", "POST"); //同意的请求方法，通常是GET,POST,PUT,DELETE,OPTIONS
        response.setHeader("Access-Control-Allow-Headers", "application/json;charset=UTF-8"); //同意哪些请求头能够跨域
        Map<Integer, Boolean> map = new HashMap<>();
        map.put(0, scoreService.update(api));
        return map;
    }

    @RequestMapping(value = "/score/updateMy", method = RequestMethod.POST)
    @ResponseBody
    public JSONResultUtil updateMy(@RequestBody List<ScoreResult> lists) {
        HttpHeaders headers = new HttpHeaders();
        try {
            if (scoreService.updateMy(lists)) {
                List<ScoreResult> list = new ArrayList<>();
                for (ScoreResult scoreResult : lists) {
                    if (scoreResult != null) {
                        list.add(scoreResult);
                    }
                }
                System.out.println(list);
                System.out.println("====");
                String json = JSON.toJSONString(list);
                System.out.println("json:" + json);
                if (updateCrmScore(headers, json)) {
                    result.setId(0);
                    result.setData("更新成功！");
                } else {
                    result.setId(-1);
                    result.setData("考试平台同步失败哦！");
                }
            } else {
                result.setId(-1);
                result.setData("更新失败哦！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setId(-1);
            result.setData("服务器异常，请联系管理员哦！");
        }
        return result;
    }

    public boolean updateCrmScore(@RequestHeader HttpHeaders headers, String json) {
        System.out.println("=========");
        headers.setContentType(MediaType.APPLICATION_JSON);
        String url = "http://114.55.144.40:8850/factory/updateCrmScore";
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> entity = restTemplate.postForEntity(url, json, Map.class);
        System.out.println(entity.getBody());
        return (boolean) entity.getBody().get("0");
    }

}
